<template>
    <div v-loading="dataLoading" class="copy-user">
        <div class="title-box">
            <div>New User Email Address:</div>
            <el-select v-model="email" value-key="user" :reserve-keyword="false" style="flex:1;" multiple
                placeholder="please input email..." size="small" filterable remote :remote-method="suggestSearch"
                :loading="emailLoading" default-first-option>
                <el-option v-for="item in options" :key="item.email" :label="item.email" :value="item"></el-option>
            </el-select>
        </div>
        <div class="transfer">
            <div class="panel">
                <div class="panel-top">
                    <el-checkbox v-model="leftCheckAll" label="Existing User List" size="large"
                        @change="checkBoxUserChange"></el-checkbox>
                    <span> {{ leftLength }}</span>
                </div>
                <div class="filter">
                    <el-input v-model="filter.email" placeholder="please input email..." size="small"
                        @keyup="val => handleEnter(val, 0)">
                        <template #suffix>
                            <el-icon @click="hanldeSearch(0)">
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>
                </div>
                <div class="padding-box">
                    <el-check-group v-model="leftSelected" @change="checkLeftChange">
                        <div class="panel-item" v-for="(item, index) in filterLeftList" :key="index">
                            <label>
                                <el-checkbox :label="item.userId"> {{ item.email }}</el-checkbox>
                            </label>
                        </div>
                    </el-check-group>
                </div>
            </div>
            <div class="btn-box">
                <div class="transfer-btn" @click="handleToLeft" :class="{ 'allowed': rightSelected.length > 0 }">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                </div>
                <div class="transfer-btn" @click="handleToRight" :class="{ 'allowed': leftSelected.length > 0 }">
                    <el-icon>
                        <ArrowRight />
                    </el-icon>
                </div>
            </div>
            <div class="panel">
                <div class="panel-top">
                    <el-checkbox v-model="rightCheckAll" label="Existing User List" size="large"
                        @change="checkBoxRoleChange"></el-checkbox>
                    <span> {{ rightLength }}</span>
                </div>
                <div class="filter">
                    <el-input v-model="filter.role" placeholder="please input email..." size="small"
                        @keyup="val => handleEnter(val, 1)">
                        <template #suffix>
                            <el-icon @click="hanldeSearch(1)">
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>
                </div>
                <div class="padding-box">
                    <el-check-group v-model="rightSelected" @change="checkRightChange">
                        <div class="panel-item" v-for="(item, index) in filterRightList" :key="index">
                            <label>
                                <el-checkbox :label="item.id"> {{ item.roleName }}</el-checkbox>
                            </label>
                        </div>
                    </el-check-group>
                </div>

            </div>
        </div>
        <div class="dialog-footer">
            <el-button class="bg-white bg-100" @click="close(false)">Cancel</el-button>
            <el-button class="bg-black bg-100" :disabled="loading || (email.length === 0)" @click="confirm">Ok</el-button>
        </div>
    </div>
</template>
<script>
import { defineComponent, ref, reactive, onUnmounted, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios'
export default defineComponent({
    name: 'CopyUser',
    setup(props, { emit }) {
        let dataLoading = ref(false);
        let loading = ref(false);
        let leftSelected = ref([]);
        let rightSelected = ref([]);
        let leftList = ref([]);
        let filterLeftList = ref([]);
        let rightList = ref([]);
        let filterRightList = ref([])
        let filter = reactive({
            email: '',
            role: ''
        })
        let leftCheckAll = ref(false);
        let leftLength = ref(0);
        let rightCheckAll = ref(false);
        let rightLength = ref(0);
        let timeTask = ref(null);

        let email = ref([]);
        let emailLoading = ref(false);
        let options = ref([]);
        let cancelToken = reactive({ cancel: null });
        let suggestSearchRes = ref(null);
        let timeout = ref(null);

        onMounted(async () => {
            dataLoading.value = true;
            await getUser();
            dataLoading.value = false;
        })
        onUnmounted(() => {
            timeTask.value = null;
        })

        const getUser = async () => {
            let res = await getApi(0);
            leftList.value = res.data || [];
            filterLeftList.value = leftList.value;
            leftLength.value = filterLeftList.value.length;
        }

        const suggestSearch = (str) => {
            clearTimeout(timeout.value);
            emailLoading.value = false;
            if (str === '') {
                options.value = [];
                return;
            }
            emailLoading.value = true;
            options.value = [];
            if (!!suggestSearchRes.value) {
                cancelToken.cancel()
            }
            timeout.value = setTimeout(() => {
                getSuggestion(encodeURIComponent(str));
                clearTimeout(timeout.value);
            }, 500)
        }
        const getSuggestion = async (param) => {
            let CancelToken = axios.CancelToken;
            let cancelTokenConfig = {
                cancelToken: new CancelToken(function excutor(c) {
                    cancelToken.cancel = c;
                })
            }
            const res = await getApi(1);
            options.value = [];
            emailLoading.value = false;
            suggestSearchRes.value = res;
            if (!res) return;
            if (res.code === 200) {
                options.value = res.data;
            }
        }

        const handleEnter = (type) => {
            if (type === 0) {
                filterLeftList.value = leftList.value.filter(item => {
                    return item.email.toLowerCase().includes(filter.email.toLowerCase());
                })
                leftLength.value = filterLeftList.value;
                leftSelected.value = leftSelected.value.filter(item => {
                    return filterLeftList.value.findIndex(v => v.userId === item) !== -1;
                })
                checkLeftChange();
            } else {
                filterRightList.value = rightList.value.filter(item => {
                    return item.roleName.toLowerCase().includes(filter.role.toLowerCase());
                })
                rightLength.value = filterRightList.value;
                rightSelected.value = rightSelected.value.filter(item => {
                    return filterRightList.value.findIndex(v => v.id === item) !== -1;
                })
                checkRightChange();
            }
        }
        const checkBoxUserChange = (value) => {
            if (value) {
                leftSelected.value = filterLeftList.value.map(item => {
                    return item.userId;
                })
            } else {
                leftSelected.value = [];
            }
        }

        const checkBoxRoleChange = (value) => {
            if (value) {
                rightSelected.value = filterRightList.value.map(item => {
                    return item.id;
                })
            } else {
                rightSelected.value = [];
            }
        }
        const checkLeftChange = () => {
            let roles = [];
            leftSelected.value.forEach(item => {
                let index = leftList.value.findIndex(v => v.userId === item);
                roles.push(...leftList.vaue[index].roles)
            })
            let idList = {};
            roles = rolse.reduce((a, b) => {
                idList[b.id] ? '' : (idList[b.id] = true && a.push(b))
            }, [])
            rightList.value = roles;
            filterRightList.value = rightList.value;
            rightSelected.value = filterRightList.value.map(item => item.id);
            rightLength.value = rightSelected.value.length;
            filterRightList.value.length === 0 ? (rightCheckAll.value = false) : (rightCheckAll.value = true)
            leftSelected.value.length === filterLeftList.value.length ? (leftCheckAll.value = true) : (leftCheckAll.value = false)
        }
        const checkRightChange = () => {
            rightList.value.length === 0 ? (rightCheckAll.value = false) : (rightCheckAll.value = true)
            rightSelected.value.length === filterRightList.value.length ? (rightCheckAll.value = true) : (rightCheckAll.value = false)
        }

        const close = (reload) => {
            emit('closeAddDialog', reload)
        }
        const confirm = () => {
            ElMessageBox.confirm('确定将已选择权限列表作为该用户的最终吗？', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                center: true,
                confirmButtonClass: 'bg-blue',
                cancelButtonClass: 'bg-black',
            }).then(async => {
                loading.value = true;
                let roles = filterRightList.value.filter(item => {
                    return rightSelected.value.indexOf(item.id) > -1;
                })
                let param = email.value.map(item => {
                    return { ...item, roles }
                })
                loading.valel = false;
                let res = await getApi(2);
                ElMessage.success({
                    message: '已添加该用户配置',
                    duration: 3000,
                    onClose: () => {
                        emit('userClose', 2)
                    }
                })
            }).catch(e => { })
        }
        const getRoleList = (type) => {
            let arr = [];
            if (type === 0) {
                arr = {
                    data: [
                        {
                            userId: 1,
                            email: '3185281991@qq.com1',
                        },
                        {
                            userId: 2,
                            email: '3185281991@qq.com2',
                        },
                        {
                            userId: 3,
                            email: '3185281991@qq.com3',
                        },
                        {
                            userId: 4,
                            email: '3185281991@qq.com4',
                        },
                        {
                            userId: 5,
                            email: '3185281991@qq.com5',
                        },
                        {
                            userId: 6,
                            email: '3185281991@qq.com6',
                        },],
                    code: 200
                }
            } else if (type == 1) {
                arr = {
                    data: [
                        {
                            userId: 1,
                            email: '3185281991@qq.com1',
                        },
                        {
                            userId: 2,
                            email: '3185281991@qq.com2',
                        },
                        {
                            userId: 3,
                            email: '3185281991@qq.com3',
                        },
                        {
                            userId: 4,
                            email: '3185281991@qq.com4',
                        },
                        {
                            userId: 5,
                            email: '3185281991@qq.com5',
                        },
                        {
                            userId: 6,
                            email: '3185281991@qq.com6',
                        }],
                    code: 200
                }
            } else {
                arr = {
                    code: 200
                }
            }
            return arr
        }
        return {
            dataLoading,
            loading,
            leftSelected,
            rightSelected,
            filterLeftList,
            filterRightList,
            filter,
            leftCheckAll,
            leftLength,
            rightCheckAll,
            rightLength,
            email,
            emailLoading,
            options,
            suggestSearch,
            handleEnter,
            checkBoxUserChange,
            checkBoxRoleChange,
            checkLeftChange,
            checkRightChange,
            close,
            confirm,
        }
    }
})
</script>
<style lang="scss" scoped>
.copy-user {
    height: 100%;
}

.title-box {
    display: flex;
    margin: 0 auto 20px;

    div:nth-child(1) {
        margin-right: 15px;
    }
}

.transfer {
    height: calc(100% - 102px);
    display: flex;

    :deep(.el-check .el-checkbox__inner) {
        width: 19px;
        height: 19px;
    }

    :deep(.el-checkbox .el-checkbox__inner::after) {
        left: 7px !important;
        top: 4px !important;
        height: 6px;
        width: 3px;
    }

    .panel {
        flex: 1;
        border: 1px solid rgba(223, 223, 223, 1);

        .panel-top {
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1px 15px;
            background-color: #f5f5f5;
        }

        span: {
            color: #909399;
        }
    }

    .filter {
        padding: 15px;
    }

    .padding-box {
        height: calc(100% - 84px);
        padding: 0 15px;
        overflow: auto;
    }

    .btn-box {
        flex-basis: 96px;
        align-self: center;
        justify-self: center;
        display: inline-block;
        vertical-align: middle;
        padding: 0 30px;

        .transfer-btn {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border: 1px solid #333;
            color: rgba(4, 100, 243, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: not-allowed;

            i {
                color: #333;
                font-weight: bold;
            }
        }

        .transfer-btn:nth-child(1) {
            margin-bottom: 50px;
        }

        .allowed {
            border: 1px solid rgba(4, 100, 243, 1);
            cursor: pointer;

            i {
                color: rgba(4, 100, 243, 1);
            }
        }
    }
}

.dialog-footer {
    margin: 15px auto;
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
}
</style>